package com.readbook.fileimage;

/**
 * Created by LHJ on 2018/6/23.
 */
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.*;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class ImgEditor{
    /**
     * 改变图片尺寸
     * @param srcFileName 源图片路径
     * @param tagFileName 目的图片路径
     * @param width 修改后的宽度
     * @param height 修改后的高度
     */
    public void zoomImage(String srcFileName,String tagFileName,int width,int height){
        try {
            BufferedImage bi = ImageIO.read(new File(srcFileName));
            BufferedImage tag=new BufferedImage(width,height, BufferedImage.TYPE_INT_RGB);
            tag.getGraphics().drawImage(bi, 0, 0, width, height, null);
            ImageIO.write(tag, "jpg", new File(tagFileName));//画图
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



    /**
     * 缩放图像（按高度和宽度缩放）
     * @param srcImageFile 源图像文件地址
     * @param result 缩放后的图像地址
     * @param height 缩放后的高度
     * @param width 缩放后的宽度
     * @param bb 比例不对时是否需要补白：true为补白; false为不补白;
     */
    public void scale(String srcImageFile, String result, int height, int width, boolean bb) {
        try {
            double ratio = 0.0; // 缩放比例
            File f = new File(srcImageFile);
            BufferedImage bi = ImageIO.read(f);
            Image itemp = bi.getScaledInstance(width, height, bi.SCALE_SMOOTH);
            // 计算比例
            if ((bi.getHeight() > height) || (bi.getWidth() > width)) {
                if (bi.getHeight() > bi.getWidth()) {
                    ratio = (new Integer(height)).doubleValue()
                            / bi.getHeight();
                } else {
                    ratio = (new Integer(width)).doubleValue() / bi.getWidth();
                }
                AffineTransformOp op = new AffineTransformOp(AffineTransform
                        .getScaleInstance(ratio, ratio), null);
                itemp = op.filter(bi, null);
            }
            if (bb) {//补白
                BufferedImage image = new BufferedImage(width, height,
                        BufferedImage.TYPE_INT_RGB);
                Graphics2D g = image.createGraphics();
                g.setColor(Color.white);
                g.fillRect(0, 0, width, height);
                if (width == itemp.getWidth(null))
                    g.drawImage(itemp, 0, (height - itemp.getHeight(null)) / 2,
                            itemp.getWidth(null), itemp.getHeight(null),
                            Color.white, null);
                else
                    g.drawImage(itemp, (width - itemp.getWidth(null)) / 2, 0,
                            itemp.getWidth(null), itemp.getHeight(null),
                            Color.white, null);
                g.dispose();
                itemp = image;
            }
            ImageIO.write((BufferedImage) itemp, "JPEG", new File(result));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 图像切割(按指定起点坐标和宽高切割)
     * @param srcImageFile 源图像地址
     * @param result 切片后的图像地址
     * @param x 目标切片起点坐标X
     * @param y 目标切片起点坐标Y
     * @param width 目标切片宽度
     * @param height 目标切片高度
     */
    public void cut(String srcImageFile, String result,
                    int x, int y, int width, int height) {
        try {
            // 读取源图像
            BufferedImage bi = ImageIO.read(new File(srcImageFile));
            int srcWidth = bi.getHeight(); // 源图宽度
            int srcHeight = bi.getWidth(); // 源图高度
            if (srcWidth > 0 && srcHeight > 0) {
                Image image = bi.getScaledInstance(srcWidth, srcHeight,
                        Image.SCALE_DEFAULT);
                // 四个参数分别为图像起点坐标和宽高
                // 即: CropImageFilter(int x,int y,int width,int height)
                ImageFilter cropFilter = new CropImageFilter(x, y, width, height);
                Image img = Toolkit.getDefaultToolkit().createImage(
                        new FilteredImageSource(image.getSource(),
                                cropFilter));
                BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
                Graphics g = tag.getGraphics();
                g.drawImage(img, 0, 0, width, height, null); // 绘制切割后的图
                g.dispose();
                // 输出为文件
                ImageIO.write(tag, "JPEG", new File(result));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //获得文件名字
    public String getFileName(MultipartFile file, HttpServletRequest request, HttpSession session){
        String FILE_PATH = session.getServletContext().getRealPath("/") + "upload";
        String fileName = file.getOriginalFilename();
        String[] suffixNameArr = fileName.split("\\.");
        String suffixName = suffixNameArr[suffixNameArr.length-1];
        String path = request.getSession().getServletContext().getRealPath("upload");
        String userName = new File(path).getName();

        return getTime() + "."+suffixName;
    }
    //文件上传,返回文件路径
    public String uploadFile(MultipartFile file, HttpServletRequest request, HttpSession session) throws IOException {
        String upload= "upload";
        String FILE_PATH = session.getServletContext().getRealPath("/") + upload;
        String fileName = getFileName(file,request,session);
        File tempFile = new File(FILE_PATH, fileName);

        if (!tempFile.getParentFile().exists()) {
            tempFile.getParentFile().mkdir();
        }
        if (!tempFile.exists()) {
            tempFile.createNewFile();
        }
        file.transferTo(tempFile);  //将上传文件写到服务器上指定的文件。

        return upload+ "\\" + tempFile.getName();
    }

   /* public static File getFile(String fileName) {
        return new File(FILE_PATH, fileName);
    } */

    public String getTime(){
        Date date = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");//设置日期格式
        String nowTime = df.format(date).toString();
        return nowTime;
    }





    //文件上传,返回文件路径
    public Map<String, Object> uploadFilemap(MultipartFile file, HttpServletRequest request, HttpSession session) throws IOException {
        String upload= "upload";
        Map<String,Object>  filesvalue = new HashMap<String,Object>();
        String FILE_PATH = session.getServletContext().getRealPath("/") + upload;
        String fileName = getFileName(file,request,session);

        File tempFile = new File(FILE_PATH, fileName);

        if (!tempFile.getParentFile().exists()) {
            tempFile.getParentFile().mkdir();
        }
        if (!tempFile.exists()) {
            tempFile.createNewFile();
        }
        file.transferTo(tempFile);  //将上传文件写到服务器上指定的文件。
        String FILE_NAME=tempFile.getName();
        String FILE_PATH1=upload+ "/" + tempFile.getName();
        String DISK_FILE_NAME = file.getOriginalFilename();
        String[] suffixNameArr = fileName.split("\\.");
        String suffixName = suffixNameArr[suffixNameArr.length-1];
        String FILE_TYPE=suffixName;
        long FILE_SIZE=file.getSize();
        filesvalue.put("FILE_NAME",FILE_NAME);
        filesvalue.put("DISK_FILE_NAME",DISK_FILE_NAME);
        filesvalue.put("FILE_TYPE",FILE_TYPE);
        filesvalue.put("FILE_SIZE",FILE_SIZE);
        filesvalue.put("FILE_PATH",FILE_PATH1);
        return filesvalue;
    }


    /**
     * @param resp
     * @param fileurl         文件路径
     */
    public static void downloadfile(HttpServletResponse resp, HttpServletRequest request, HttpSession session, String fileurl) {
        String realPath =session.getServletContext().getRealPath("/") ;
        String path = realPath + File.separator + fileurl;
        File file = new File(path);
        String fileName =file.getName();

        resp.reset();
        resp.setContentType("application/octet-stream");
        resp.setCharacterEncoding("utf-8");
        resp.setContentLength((int) file.length());
        resp.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        OutputStream os = null;
        try {
            os = resp.getOutputStream();
            bis = new BufferedInputStream(new FileInputStream(file));
            int i = 0;
            while ((i = bis.read(buff)) != -1) {
                os.write(buff, 0, i);
                os.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                bis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }





    //文件上传,返回文件路径
    public Map<String, Object> uploadFilemapGetFilename(MultipartFile file, HttpServletRequest request, HttpSession session,String filename) throws IOException {
        String upload= "upload";
        String uploadpath= session.getServletContext().getRealPath("/") + upload;
        File uploadfile = new File(uploadpath);
        if (!uploadfile.exists()) {
            uploadfile.mkdir();
        }

        Map<String,Object>  filesvalue = new HashMap<String,Object>();
        String FILE_PATH = session.getServletContext().getRealPath("/") + upload+"/"+filename;
        String fileName = getFileName(file,request,session);

        File tempFile = new File(FILE_PATH, fileName);

        if (!tempFile.getParentFile().exists()) {
            tempFile.getParentFile().mkdir();
        }
        if (!tempFile.exists()) {
            tempFile.createNewFile();
        }
        file.transferTo(tempFile);  //将上传文件写到服务器上指定的文件。
        String FILE_NAME=tempFile.getName();
        String FILE_PATH1= upload+"/"+filename+"/"+ tempFile.getName();
        String DISK_FILE_NAME = file.getOriginalFilename();
        String[] suffixNameArr = fileName.split("\\.");
        String suffixName = suffixNameArr[suffixNameArr.length-1];
        String FILE_TYPE=suffixName;
        long FILE_SIZE=file.getSize();
        filesvalue.put("FILE_NAME",FILE_NAME);
        filesvalue.put("DISK_FILE_NAME",DISK_FILE_NAME);
        filesvalue.put("FILE_TYPE",FILE_TYPE);
        filesvalue.put("FILE_SIZE",FILE_SIZE);
        filesvalue.put("FILE_PATH",FILE_PATH1);
        return filesvalue;
    }


    /**
     * 读取某个文件夹下的所有文件
     */
    public static boolean readfile(String filepath) throws FileNotFoundException, IOException {
        try {

            File file = new File(filepath);
            if (!file.isDirectory()) {
                System.out.println("文件");
                System.out.println("path=" + file.getPath());
                System.out.println("absolutepath=" + file.getAbsolutePath());
                System.out.println("name=" + file.getName());

            } else if (file.isDirectory()) {
                System.out.println("文件夹");
                String[] filelist = file.list();
                for (int i = 0; i < filelist.length; i++) {
                    File readfile = new File(filepath + "\\" + filelist[i]);
                    if (!readfile.isDirectory()) {
                        System.out.println("path=" + readfile.getPath());
                        System.out.println("absolutepath="
                                + readfile.getAbsolutePath());
                        System.out.println("name=" + readfile.getName());

                    } else if (readfile.isDirectory()) {
                        readfile(filepath + "\\" + filelist[i]);
                    }
                }

            }

        } catch (FileNotFoundException e) {
            System.out.println("readfile()   Exception:" + e.getMessage());
        }
        return true;
    }



    public static void main(String args[])throws Exception{
        Calendar cale = null;
        cale = Calendar.getInstance();
        int nowyear = cale.get(Calendar.YEAR);
        System.out.print(nowyear);
    }

}
